import { routeEqual } from "_/utils/tools";

/**
 * 获取用户拥有权限的菜单列表
 * @param {Array} premissions 权限清单
 * @param {Array} routes 路由清单
 * @returns {Array}
 */
export function getMenus(premissions, routes) {
  const isAdmin = premissions.length === 0;

  const hasPower = (item) => {
    let meta = item.meta || {};
    let powers = meta.powers || [];
    if (isAdmin || powers.length === 0) {
      return true;
    }
    return powers.find(power => premissions.indexOf(`${item.name}-${power.code}`) > -1);
  }

  const showInMenu = (item) => !(item.meta || {}).hideInMenu;

  const fatch = (source) => {
    let res = [];
    if (!Array.isArray(source)) {
      return res;
    }
    source.forEach(item => {
      if (!hasPower(item) || !showInMenu(item)) {
        return;
      }
      const { name, meta, children } = item;
      let obj = {
        name,
        meta,
        icon: meta.icon,
        powers: meta.powers || [],
        href: meta.href,
        children: fatch(children)
      };
      if (children && obj.children.length == 0) {
        return;
      }
      if (obj.meta.isGroup) {

      } else if (obj.children.length == 1) {
        let child = obj.children[0];
        child.icon = child.icon || obj.icon
        obj = child;
      }
      res.push(obj);
    });
    res = res.sort((a, b) => a.meta.sort - b.meta.sort);
    return res
  };

  return fatch(routes);
};

/**
 * @param {Number} times 回调函数需要执行的次数
 * @param {Function} callback 回调函数
 */
function doCustomTimes(times, callback) {
  let i = -1;
  while (++i < times) {
    callback(i)
  }
};

/**
 * 判断打开的标签列表里是否已存在这个新添加的路由对象
 */
export function routeHasExist(tags, routeItem) {
  let len = tags.length;
  let res = false;
  doCustomTimes(len, (index) => {
    if (routeEqual(tags[index], routeItem)) res = true
  });
  return res
};

/**
 * @param {Array} list 标签列表
 * @param {String} name 当前关闭的标签的name
 */
export function nextRoute(list, route) {
  let res = {};
  if (list.length === 2) {
    res = list[0];
  } else {
    const index = list.findIndex(item => routeEqual(item, route));
    if (index === list.length - 1) res = list[list.length - 2];
    else res = list[index + 1]
  }
  return res
};

/**
 * 查找路由列表（routes）中name为routeName的对象
 * @param {Array} routes 路由列表数组
 * @param {string} routeName 需要查找路由名称
 */
export function findRoute(routes, routeName) {
  if (!routes) return undefined;
  let result = routes.find(p => p && p.name === routeName);
  !result && routes.forEach(route => {
    !result && (result = findRoute(route.children, routeName));
  });
  return result;
};
